#coding:utf-8
from alipay import AliPay
import time,os,sys,json
from app import db
from app.home import home
from flask import request, jsonify,session,g,current_app
from app.models import User
from response_code import RET
from error_msg import  LoggerError
from app.func.get_token import get_token_by_pwd,get_token_by_code
from app.func.token_auth import  auth as http_auth

@home.route("/mall/login",methods=["POST"])
def mall_login():
    user_data=request.get_json()
    print(user_data)
    user_login_method=user_data.get("loginMehohd")
    phone=user_data.get("phone")
    password = user_data.get("password")
    code=user_data.get("cdoe")
    if user_login_method:
        print(user_login_method)
        # 验证码登录
        if user_login_method==2:
            uuid = int(time.time() * 1000000)  # uuid暂时用时间戳替代
            if not all([phone, code, uuid]):
                return jsonify({"code": RET.PARAMERR, "message": "参数不完整"})
            try:
                user = User.query.filter_by(phone=phone).first()
            except:
                return jsonify({"code": RET.DBERR, 'message': '数据库错误'})
            if not user:
                return jsonify({"code": RET.OK, 'message': '注册新用户',"user_status":1})
            t=get_token_by_code(user,uuid)
        # 密码登录
        if user_login_method==1:
            uuid = int(time.time() * 1000000)  # uuid暂时用时间戳替代
            if not all([phone, password, uuid]):
                return jsonify({"code": RET.PARAMERR, "message": "参数不完整"})
            try:
                user = User.query.filter_by(phone=phone).first()
            except:
                return jsonify({"code": RET.DBERR, 'message': '数据库错误'})
            if not user:
                return jsonify({"code": RET.OK, 'message': '注册新用户', "user_status": 1,"user_login_method":user_login_method})
            t=get_token_by_pwd(user.id,uuid)
            user_data={
                "name":user.name,
                "phone":phone,
                "order":"order"
            }
        return jsonify(code=RET.OK, message="登录成功", data=t,user_data=user_data)


@home.route("/mall/user_info",methods=["GET"])
@http_auth.login_required
def get_user_info():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR, msg="无权请求此接口", data="")
    uid=g.user_id
    try:
        user=db.session.query(User).filter(User.id==uid).first()
    except Exception as e:
        return  jsonify(code=RET.DBERR,msg="数据库查询错误")
    if not user:
        return jsonify(code=RET.NODATA, msg="查询不到此用户")
    user_info={
        "name":user.name,
        "phone":user.phone,
        "order":"order"
    }
    print(user_info)
    return jsonify(code=RET.OK,msg="获取用户信息成功",user_info=user_info)




